<template>
  <div class="football-editor-view">
    <el-row :gutter="20">
      <!-- Left side: Icon management -->
      <el-col :span="6">
        <el-card class="icon-management card-container">
          <template #header>
            <div class="card-header">
              <h3>图标管理</h3>
              <el-radio-group v-model="iconType" size="small">
                <el-radio-button label="team">球队图标</el-radio-button>
                <el-radio-button label="match">比赛图标</el-radio-button>
              </el-radio-group>
            </div>
          </template>

          <icon-list :icon-type="iconType" :key="iconType + '-' + refreshKey" @icon-updated="handleIconUpdated"
            @icon-deleted="handleIconDeleted" @icon-clicked="handleIconClicked"
            @upload-clicked="uploadDialogVisible = true" />
        </el-card>
      </el-col>

      <!-- Right side: Subtitle selection -->
      <el-col :span="6">
        <el-card class="card-container">
          <template #header>
            <div class="card-header">
              <h3>选择字幕文件</h3>
            </div>
          </template>
          <subtitle-selector @select-subtitle="handleSubtitleSelected" ref="subtitleSelectorRef" />
        </el-card>
      </el-col>

      <!-- Video browser -->
      <el-col :span="4">
        <el-card  class="card-container">
          <template #header>
            <div class="card-header">
              <h3>视频预览</h3>
            </div>
          </template>
          <video-browser 
            ref="videoBrowserRef"
            :video-paths="videoPaths" 
            :generated-video-paths="generatedVideoPaths"
            :default-show-generated="hasGeneratedVideos"
            @toggle-video-type="handleToggleVideoType"
          />
        </el-card>
      </el-col>

      <!-- Subtitle editor -->
      <el-col :span="8">
        <el-card class="card-container">
          <template #header>
            <div class="card-header">
              <h3>字幕编辑器</h3>
            </div>
          </template>
          <subtitle-editor 
            ref="subtitleEditorRef" 
            :filename="selectedFilename" 
            :key="selectedFilename"
            :is-generating="isGeneratingVideo"
            @generate-video="handleGenerateVideo" 
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- Icon upload dialog -->
    <el-dialog v-model="uploadDialogVisible" title="上传图标" width="30%" :destroy-on-close="true">
      <icon-form :icon-type="iconType" @upload-success="handleIconUploaded" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import IconForm from './components/IconForm.vue';
import IconList from './components/IconList.vue';
import SubtitleSelector from './components/SubtitleSelector.vue';
import SubtitleEditor from './components/SubtitleEditor.vue';
import footballService from './services/footballService';
import VideoBrowser from './components/VideoBrowser.vue';
import { genOutsideVideoURL } from '@/utils/videoHelper.js';

const iconType = ref('team');
const refreshKey = ref(0);
const uploadDialogVisible = ref(false);
const subtitleEditorRef = ref(null);
const videoBrowserRef = ref(null);
const subtitleSelectorRef = ref(null);
const videoPaths = ref([]);
const generatedVideoPaths = ref([]);
const selectedFilename = ref('');
const currentSubtitleData = ref(null);

// 计算属性，用于判断是否有生成的视频
const hasGeneratedVideos = computed(() => {
  return generatedVideoPaths.value.length > 0;
});

// 添加一个状态来跟踪视频是否正在生成
const isGeneratingVideo = ref(false);

// Icon management handlers
const handleIconUploaded = () => {
  ElMessage.success('图标上传成功');
  refreshKey.value++; // Trigger list refresh
  uploadDialogVisible.value = false;
};

const handleIconUpdated = () => {
  ElMessage.success('图标更新成功');
  refreshKey.value++;
};

const handleIconDeleted = () => {
  ElMessage.success('图标删除成功');
  refreshKey.value++;
};

// 刷新当前字幕数据
const refreshCurrentSubtitle = async () => {
  if (!currentSubtitleData.value || !currentSubtitleData.value.id) return;
  
  try {
    // 获取最新的字幕数据
    const response = await footballService.getSubtitleById(currentSubtitleData.value.id);
    if (response && response.data) {
      // 更新当前字幕数据
      currentSubtitleData.value = response.data;
      
      // 更新字幕选择器中的对应数据
      if (subtitleSelectorRef.value) {
        subtitleSelectorRef.value.updateSubtitleData(response.data);
      }
      
      // 更新生成的视频路径
      const iconVideoPaths = currentSubtitleData.value.meta_data?.icon_video_paths || [];
      generatedVideoPaths.value = iconVideoPaths.map(path => genOutsideVideoURL(path));
      
      // 如果有生成的视频，自动切换到生成视频预览
      if (generatedVideoPaths.value.length > 0 && videoBrowserRef.value) {
        videoBrowserRef.value.setShowGeneratedVideos(true);
      }
      
      // 刷新视频预览
      if (videoBrowserRef.value) {
        videoBrowserRef.value.refreshVideos();
      }
    }
  } catch (error) {
    console.error('刷新字幕数据失败:', error);
    ElMessage.error('刷新字幕数据失败');
  }
};

const handleGenerateVideo = () => {
  // 如果正在生成视频，则不执行操作
  if (isGeneratingVideo.value) return;
  
  // 设置正在生成视频状态
  isGeneratingVideo.value = true;
  
  footballService.generateIconVideos(videoPaths.value, currentSubtitleData.value.id)
    .then(() => {
      ElMessage.success('视频生成成功');
      
      // 刷新字幕数据以获取更新的 icon_video_paths
      refreshCurrentSubtitle();
    })
    .catch((error) => {
      console.error('生成视频失败:', error);
      ElMessage.error('生成视频失败，请稍后重试');
    })
    .finally(() => {
      // 无论成功还是失败，都将状态重置
      isGeneratingVideo.value = false;
    });
};

const handleToggleVideoType = (showGenerated) => {
  if (videoBrowserRef.value) {
    videoBrowserRef.value.setShowGeneratedVideos(showGenerated);
  }
};

// Icon clicked - insert icon name into subtitle editor
const handleIconClicked = (icon) => {
  if (subtitleEditorRef.value) {
    const subtitleText = generateSubtitleText(icon);
    subtitleEditorRef.value.insertText(subtitleText);
  }
};

const generateSubtitleText = (icon) => {
  return `[${icon.file_type}:${icon.meta_data.icon_type}:${icon.id}:${icon.filename}]`;
}

// 选择字幕文件
const handleSubtitleSelected = (file) => {
  // 如果选择了与当前相同的字幕，且我们已有数据，直接使用
  if (currentSubtitleData.value && currentSubtitleData.value.id === file.id) {
    // 已是当前字幕，无需重新加载
    return;
  }
  
  selectedFilename.value = file.id;
  currentSubtitleData.value = file;
  
  // 更新原始视频路径
  let video_paths = file?.meta_data?.video_paths || [];
  video_paths = video_paths.map((path) => {
    return genOutsideVideoURL(path);
  });
  videoPaths.value = video_paths;
  
  // 更新生成的视频路径(如果有)
  const iconVideoPaths = file?.meta_data?.icon_video_paths || [];
  generatedVideoPaths.value = iconVideoPaths.map(path => genOutsideVideoURL(path));
  
  // 决定默认显示哪种视频 - 如果有生成的视频则显示生成的视频
  if (videoBrowserRef.value) {
    videoBrowserRef.value.setShowGeneratedVideos(generatedVideoPaths.value.length > 0);
    videoBrowserRef.value.refreshVideos();
  }
};
</script>

<style scoped>
.football-editor-view {
  width: 100%;
}

.card-container {
  height: calc(100vh - 100px);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.icon-management,
.subtitle-editor {
  overflow: auto;
}
</style>